package cn.xuewenbao.edu.service.impl;

import cn.xuewenbao.edu.controller.ESController;
import cn.xuewenbao.edu.entity.*;
import cn.xuewenbao.edu.entity.vo.*;
import cn.xuewenbao.edu.mapper.BookMapper;
import cn.xuewenbao.edu.service.*;
import cn.xuewenbao.ucenter.service.MemberService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 讲书表 服务实现类
 * </p>
 *
 * @author mafayu
 * @since 2021-03-30
 */
@Service
@Slf4j
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {

    private static final String BOOK_TYPE = "4";
    @Autowired
    private LikeContentService likeContentService;

    @Autowired
    private FavoriteService favoriteService;

    @Autowired
    private ColumnDataService columnDataService;

    @Autowired
    private GoodLinkService linkService;

    @Autowired
    private ContentSubjectService contentSubjectService;

    @Autowired
    private ESController esController;

    @Autowired
    private MemberService memberService;

    @Autowired
    private ViewContentService viewContentService;

    @Autowired
    private LearnRecordService learnRecordService;

    //获取讲书列表
    @Override
    public List<BookInfoVo> listAllArticle() {
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status","Approval");
        List<Book> bookList = baseMapper.selectList(queryWrapper);
        List<BookInfoVo> bookInfoVoList = new ArrayList<>();
        for (int i = 0; i < bookList.size(); i++) {
            BookInfoVo bookInfoVo = new BookInfoVo();
            BeanUtils.copyProperties(bookList.get(i), bookInfoVo);
            bookInfoVoList.add(bookInfoVo);
        }
        return bookInfoVoList;
    }

    //根据用户id获取荐书列表
    @Override
    public List<BookIndexVo> listIndexBook(String userId) {
        QueryWrapper<Book> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.eq("status","Approval");
        wrapper.orderByDesc("like_count");
        List<Book> bookList = baseMapper.selectList(wrapper);
        List<BookIndexVo> bookIndexVoList = new ArrayList<>();
        for (int i = 0; i < bookList.size(); i++) {
            BookIndexVo bookIndexVo = new BookIndexVo();
            BeanUtils.copyProperties(bookList.get(i), bookIndexVo);
            bookIndexVoList.add(bookIndexVo);
        }
        return bookIndexVoList;
    }

    //根据讲书id获取讲书详情-音频
    @Override
    public Result<BookDetailAudioVo> getBookAudioDetail(String bookId, String userId) {
        Result<BookDetailAudioVo> result = new Result<>();
        Book book = baseMapper.selectById(bookId);
        if (book == null) {
            result.setSuccess(false);
            result.setMessage("不存在该讲书");
            return result;
        }
        //阅读数加1
        book.setViewCount(book.getViewCount()+1);
        baseMapper.updateById(book);

        //将阅读记录添加到阅读表中
        ViewContent viewContent = new ViewContent();
        viewContent.setContentId(bookId);
        viewContent.setColumnType(BOOK_TYPE);
        viewContent.setAuthorId(book.getUserId());
        viewContent.setUserId(userId);
        viewContentService.save(viewContent);

        BookDetailAudioVo bookDetailAudioVo = new BookDetailAudioVo();
        BeanUtils.copyProperties(book, bookDetailAudioVo);
        //查询是否点赞、收藏
        Result<?> isLikeResult = likeContentService.hasLikeOne(userId, bookId, BOOK_TYPE);
        bookDetailAudioVo.setIsLike(isLikeResult.isSuccess());
        Result<?> isFavoriteResult = favoriteService.hasFavoriteOne(userId, bookId, BOOK_TYPE);
        bookDetailAudioVo.setIsFavorite(isFavoriteResult.isSuccess());
        //查询点赞数、收藏数
        QueryWrapper<ColumnData> wrapper = new QueryWrapper<>();
        wrapper.eq("content_id", bookId).eq("column_type", BOOK_TYPE);
        ColumnData columnData = columnDataService.getOne(wrapper);
        if (columnData == null) {
            result.setSuccess(false);
            result.setMessage("讲书内容的数据不存在");
            return result;
        }

        columnData.setViewCount(book.getViewCount());
        columnDataService.updateById(columnData);

        bookDetailAudioVo.setLikeCount(columnData.getLikeCount());
        bookDetailAudioVo.setFavoriteCount(columnData.getFavoriteCount());

        //查询音频的播放进度
        Double currentTime = learnRecordService.getCurrentTime(userId, bookId, BOOK_TYPE, "audio");
        if (currentTime != null) {
            bookDetailAudioVo.setCurrentTime(currentTime);
        } else {
            bookDetailAudioVo.setCurrentTime(0.0);
        }

        result.setMessage("查询成功");
        result.setSuccess(true);
        result.setResult(bookDetailAudioVo);
        return result;
    }

    //根据讲书id获取讲书详情-视频
    @Override
    public Result<BookDetailVideoVo> getBookVideoDetail(String bookId, String userId) {
        Result<BookDetailVideoVo> result = new Result<>();
        Book book = baseMapper.selectById(bookId);
        if (book == null) {
            result.setSuccess(false);
            result.setMessage("不存在该讲书");
            return result;
        }
        //阅读数加1
        book.setViewCount(book.getViewCount()+1);
        baseMapper.updateById(book);

        //将阅读记录添加到阅读表中
        ViewContent viewContent = new ViewContent();
        viewContent.setContentId(bookId);
        viewContent.setColumnType(BOOK_TYPE);
        viewContent.setAuthorId(book.getUserId());
        viewContent.setUserId(userId);
        viewContentService.save(viewContent);

        //查询点赞数、收藏数
        QueryWrapper<ColumnData> wrapper = new QueryWrapper<>();
        wrapper.eq("content_id", bookId).eq("column_type", BOOK_TYPE);
        ColumnData columnData = columnDataService.getOne(wrapper);
        if (columnData == null) {
            result.setSuccess(false);
            result.setMessage("讲书内容的数据不存在");
            return result;
        }
        columnData.setViewCount(book.getViewCount());
        columnDataService.updateById(columnData);
        BookDetailVideoVo videoVo = new BookDetailVideoVo();
        BeanUtils.copyProperties(book, videoVo);

        //查询视频的播放进度
        Double currentTime = learnRecordService.getCurrentTime(userId, bookId, BOOK_TYPE, "video");
        if (currentTime != null) {
            videoVo.setCurrentTime(currentTime);
        } else {
            videoVo.setCurrentTime(0.0);
        }

        result.setMessage("查询成功");
        result.setSuccess(true);
        result.setResult(videoVo);
        return result;
    }

    //根据讲书id获取讲书购买链接
    @Override
    public Result<BookBuyLink> getBookBuyLink(String bookId) {
        Result<BookBuyLink> result = new Result<>();
        Book book = baseMapper.selectById(bookId);
        if (book == null) {
            result.setSuccess(false);
            result.setMessage("不存在该讲书");
            return result;
        }
        BookBuyLink bookBuyLink = new BookBuyLink();
        BeanUtils.copyProperties(book, bookBuyLink);

        QueryWrapper<GoodLink> goodLinkQueryWrapper = new QueryWrapper<>();
        goodLinkQueryWrapper.eq("good_id",bookId);
        GoodLink goodLink = linkService.getOne(goodLinkQueryWrapper);
        if (goodLink == null) {
            result.setSuccess(false);
            return result;
        }
        bookBuyLink.setCover(goodLink.getCover());

        result.setMessage("查询成功");
        result.setSuccess(true);
        result.setResult(bookBuyLink);
        return result;
    }

    @Override
    public Result<?> addBook(BookPulishVo bookPulishVo) {
        Result<String> result = new Result<>();
        Book book = new Book();
        if (bookPulishVo == null) {
            result.setSuccess(false);
            result.setMessage("讲书内容为空");
            result.setResult(null);
            return result;
        }
        BeanUtils.copyProperties(bookPulishVo, book);
        int insert = baseMapper.insert(book);

        //添加好物推荐
        GoodVo goodVo = bookPulishVo.getGoodVo();
        if(goodVo==null){
            result.setMessage("好物链接为空");
        }else {
            GoodLink goodLink = new GoodLink();
            BeanUtils.copyProperties(goodVo, goodLink);
            goodLink.setGoodId(book.getId());
            goodLink.setUserId(bookPulishVo.getUserId());
            goodLink.setType("book");
            linkService.save(goodLink);
            result.setMessage("添加好物链接成功");
        }


        if (insert > 0) {
            final val id = book.getId();
            val subjectList = bookPulishVo.getSubjectList();
            for (String s : subjectList) {
                ContentSubject contentSubject=new ContentSubject();
                contentSubject.setContentId(id);
                contentSubject.setSubjectId(s);
                contentSubject.setColumnType(BOOK_TYPE);
                contentSubjectService.save(contentSubject);
            }
            //为讲书添加 columnData
            Boolean dataSuccess = columnDataService.addColumnData(id, BOOK_TYPE, 0L, 0L, 0L, 0L);
            if (dataSuccess) {
                result.setSuccess(true);
                result.setMessage("添加讲书成功");
                result.setResult(id);
                return result;
            }
            return Result.error("添加讲书数据失败");
        } else {
            return Result.error("添加讲书失败");
        }
    }

    //删除讲书
    @Override
    public Result<?> deleteBook(String bookId) {
        Result<?> result = new Result<>();
        int res = baseMapper.deleteById(bookId);
        if (res == 0) {
            result.setMessage("删除讲书失败");
            result.setSuccess(false);
            return result;
        }
        result.setMessage("删除讲书成功");
        result.setSuccess(true);
        return result;
    }

    //根据id和作者id删除讲书
    @Override
    public Result<?> deleteOwnBook(String bookId, String userId) {
        Result<?> result = new Result<>();
        Book book = baseMapper.selectById(bookId);
        if (book == null) {
            result.setMessage("讲书为空");
            result.setSuccess(false);
            return result;
        }
        if (!book.getUserId().equals(userId)) {
            result.setMessage("没有删除权限");
            result.setSuccess(false);
            return result;
        }
        int res = baseMapper.deleteById(bookId);
        if (res == 0) {
            result.setMessage("删除讲书失败");
            result.setSuccess(false);
            return result;
        }
        result.setMessage("删除讲书成功");
        result.setSuccess(true);
        return result;
    }

    @Override
    public List<BookInfoVo> getCreateBookList(String userId) {
        QueryWrapper<Book> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.eq("status","Approval");
        wrapper.orderByDesc("gmt_create");
        List<Book> bookList = baseMapper.selectList(wrapper);
        List<BookInfoVo> bookIndexVoList = new ArrayList<>();
        for (int i = 0; i < bookList.size(); i++) {
            BookInfoVo bookInfoVo = new BookInfoVo();
            BeanUtils.copyProperties(bookList.get(i), bookInfoVo);
            bookIndexVoList.add(bookInfoVo);
        }
        return bookIndexVoList;
    }

}
